from django.shortcuts import render
from django.http import HttpResponse
from . models import *
import os,time

###Dashboard登录视图

#绘制验证码(需安装Pillow)
def verifycode(request):
	#引入绘图模块
	from PIL import Image, ImageDraw, ImageFont
	#引入随机函数模块
	import random
	#定义变量，用于画面的背景色、宽、高
	bgcolor = (random.randrange(20, 100), random.randrange(
	    20, 100), 255)
	width = 100
	height = 25
	#创建画面对象
	im = Image.new('RGB', (width, height), bgcolor)
	#创建画笔对象
	draw = ImageDraw.Draw(im)
	#调用画笔的point()函数绘制噪点
	for i in range(0, 100):
	    xy = (random.randrange(0, width), random.randrange(0, height))
	    fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
	    draw.point(xy, fill=fill)
	#定义验证码的备选值
	str1 = 'ABCD123EFGHJK456LMNOPQRS789TUVWXYZ0'

	#随机选取4个值作为验证码
	rand_str = ''
	for i in range(0, 4):
	    rand_str += str1[random.randrange(0, len(str1))]
	#构造字体对象
	font = ImageFont.truetype('static/myfont.TTF', 23)
	# font = ImageFont.load_default().font
	#构造字体颜色
	fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
	#绘制4个字
	draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
	draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
	draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
	draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
	#释放画笔
	del draw
	#存入session，用于做进一步验证
	request.session['verifycode'] = rand_str
	#内存文件操作
	"""
	python2的为
	# 内存文件操作
	import cStringIO
	buf = cStringIO.StringIO()
	"""
	#内存文件操作-->此方法为python3的
	import io
	buf = io.BytesIO()
	#将图片保存在内存中，文件类型为png
	im.save(buf, 'png')
	#将内存中的图片数据返回给客户端，MIME类型为图片png
	return HttpResponse(buf.getvalue(), 'image/png')

#访问dash用户登录页面
def login_page(request):
	return render(request,'dash/login.html')

#执行登录验证
def dologin(request):
	#判断验证码
	if request.session['verifycode'] != request.POST['verifycode'].upper():
		return HttpResponse('<script>alert("验证码错误");location.href="/dashboard/login_page";</script>')

	#判断登录信息是否正确
	try:
		user = Users.objects.get(username = request.POST['username'])
		#判断用户权限是否为管理员
		if user.state == 0:
			from django.contrib.auth.hashers import make_password, check_password
			#判断用户密码是否正确
			if check_password(request.POST['password'],user.pwd):
				#用户信息存入session
				request.session['user_info'] = {'user_id':user.id,'user_name':user.username,'user_hdimg':user.head_img}
				#跳转至dashboard index page
				return HttpResponse('<script>alert("登陆成功");location.href="/dashboard/index_page";</script>')
			else:
				return HttpResponse('<script>alert("用户名密码错误");location.href="/dashboard/login_page";</script>')
		else:
			return HttpResponse('<script>alert("用户不存在");location.href="/dashboard/login_page";</script>')
	except:
		return HttpResponse('<script>alert("用户名或密码错误");location.href="/dashboard/login_page";</script>')

#注销登录
def dologout(request):
	#将session置空
	request.session['user_info'] = ''

	return HttpResponse('<script>alert("注销成功");location.href="/dashboard/login_page";</script>')






		



	













